package com.carefree.system.modules.security.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.carefree.common.emus.StatusCodeEnum;
import com.carefree.common.exception.BusinessException;
import com.carefree.system.modules.admin.dao.UserDao;
import com.carefree.system.modules.admin.entity.UserEntity;
import com.carefree.system.modules.admin.service.MenuService;
import com.carefree.system.modules.security.entity.CustomUserDetails;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @ClassName:UserDetailsServiceImpl
 * @Description: 步骤二:  implements UserDetailsService, 重写loadUserByUsername(String username)方法
 * @Author Tengbin tengbin234@163.com
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserDao userDao;

    @Resource
    private MenuService menuService;


    /**
     * 获取用户信息
     *
     * @param username 用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 数据库查询用户信息
        UserEntity user = userDao.selectOne(new QueryWrapper<UserEntity>().eq("username", username));
        // 查无此人
        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException(StatusCodeEnum.NO_SUCH_ACCOUNT.getMessage());
        }
        // 被禁用
        if (user.getStatus() == 0) {
            throw new BusinessException(StatusCodeEnum.ACCOUNT_DISABLED_ERROR.getCode(), StatusCodeEnum.ACCOUNT_DISABLED_ERROR.getMessage());
        }
        // 根据用户id查询所拥有的权限列表
        List<String> permissionList = menuService.getMenuButtonsByUserId(user.getId());
        return new CustomUserDetails(user, permissionList);
    }
}
